<template>
  <div>App</div>
  <div>
    <p>count--{{ count }}</p>
    <button @click="changeCount">修改count的值</button>
  </div>

  <div>
    <p>goodsInfo--{{ goodsInfo }}</p>
    <button @click="changeGoodInfo1">修改goodsInfo的值</button>
    <button @click="changeGoodInfo2">修改goodsInfo某个属性的值</button>
    <button @click="changeGoodInfo3">修改goodsInfo中颜色对象的属性的值</button>
    <button @click="changeGoodInfo4">修改goodsInfo中skuNum的改变</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default /*#__PURE__*/ defineComponent({
  name: "App",
});
</script>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";

//1.ref数据值为基本类型
const count = ref(0);
const changeCount = () => {
  count.value++;
};
//监听
/* 
  1. 对于ref基本类型值，我们直接监听这个ref对象即可,一旦value值发生变化，即执行回调函数
*/
watch(count, (newVal, oldVal) => {
  console.log(newVal, oldVal);
});

//2.ref数据值为对象类型
const goodsInfo = ref({
  skuNum: 1,
  skuName: "Apple14",
  skuAttrList: [["白色", "黑色", "粉色"]],
});

const changeGoodInfo1 = () => {
  goodsInfo.value = {
    skuNum: 2,
    skuName: "Apple15",
    skuAttrList: [["绿色"]],
  };
};

const changeGoodInfo2 = () => {
  goodsInfo.value.skuNum = 10;
};
const changeGoodInfo3 = () => {
  goodsInfo.value.skuAttrList[0].push("蓝色");
  // goodsInfo.value.skuAttrList=[[]];
};
const changeGoodInfo4 = () => {
  goodsInfo.value.skuNum = 2;
};

/* 
  ref数据值为对象类型:
    1.直接监听ref对象,只能监听到这个对象被替换,其他的修改无法监听到(没有深度监听)
    2.监听ref对象的value属性(整个代理对象),无法监听到对象被替换,但是可以监听到对象的修改(默认深度监听)
    3.监听ref对象value值中的某个对象值类型属性(代理对象中的某个对象值类型属性),无法监听到对象被替换,但是可以监听对象内部的修改(默认深度监听)
    4.如果想要监听某个属性值是否被替换(无论值是基本类型还是对象类型),watch的第一个参数需要写成函数写法返回被监听的值`()=>被监听的值`

  reactive类型的监听
    reactive和ref是一个对象的时候规则保持一致
*/
watch(
  goodsInfo,
  (newVal, oldVal) => {
    console.log(newVal, oldVal);
  },
  {
    deep: true,
    immediate: true,
  }
);
/* watch(goodsInfo.value, (newVal, oldVal) => {
  console.log(newVal, oldVal);
}); */
/* watch(goodsInfo.value.skuAttrList, (newVal, oldVal) => {
  console.log(newVal, oldVal);
}); */

/* watch(
  () => goodsInfo.value.skuNum,
  (newVal, oldVal) => {
    console.log(newVal, oldVal);
  }
); */
</script>

<style></style>
